<template>
  <div class="import-export-container">
    <h2>导入导出</h2>

    <el-card class="import-export-card" shadow="never">
      <el-tabs type="border-card">
        <!-- 导出选项卡 -->
        <el-tab-pane label="导出Mock配置">
          <div class="export-section">
            <h3>导出所有Mock API配置</h3>
            <p>将所有Mock API配置导出为JSON文件</p>
            <el-button type="primary" @click="exportAllMockAPIs" :loading="exporting">
              导出所有配置
            </el-button>
          </div>
        </el-tab-pane>

        <!-- 导入选项卡 -->
        <el-tab-pane label="导入Mock配置">
          <div class="import-section">
            <h3>从JSON文件导入</h3>
            <p>从之前导出的JSON文件中导入Mock API配置</p>
            <el-upload
              class="upload-area"
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :limit="1"
              accept=".json"
            >
              <template #trigger>
                <el-button type="primary">选择文件</el-button>
              </template>
              <template #tip>
                <div class="el-upload__tip">
                  请选择JSON格式的配置文件
                </div>
              </template>
            </el-upload>

            <div class="import-actions" v-if="importFile">
              <p>已选择文件: {{ importFile.name }}</p>
              <el-button type="success" @click="importFromJSON" :loading="importing">
                开始导入
              </el-button>
            </div>
          </div>

          <el-divider></el-divider>

          <div class="import-section">
            <h3>从Swagger/OpenAPI导入</h3>
            <p>从Swagger或OpenAPI规范文件导入API配置</p>
            
            <el-form :model="swaggerForm" label-width="100px">
              <el-form-item label="导入方式">
                <el-radio-group v-model="swaggerForm.importType">
                  <el-radio label="file">本地文件</el-radio>
                  <el-radio label="url">远程URL</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item v-if="swaggerForm.importType === 'file'">
                <el-upload
                  class="upload-area"
                  action="#"
                  :auto-upload="false"
                  :on-change="handleSwaggerFileChange"
                  :limit="1"
                  accept=".json,.yaml,.yml"
                >
                  <template #trigger>
                    <el-button type="primary">选择Swagger文件</el-button>
                  </template>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持JSON或YAML格式的Swagger/OpenAPI文件
                    </div>
                  </template>
                </el-upload>
              </el-form-item>

              <el-form-item label="Swagger URL" v-if="swaggerForm.importType === 'url'">
                <el-input v-model="swaggerForm.url" placeholder="请输入Swagger文档URL"></el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="success" @click="importFromSwagger" :loading="importingSwagger">
                  从Swagger导入
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 导出相关
const exporting = ref(false)

// 导入相关
const importing = ref(false)
const importFile = ref(null)

// Swagger导入相关
const importingSwagger = ref(false)
const swaggerForm = reactive({
  importType: 'file',
  url: '',
  file: null
})

// 导出所有Mock API配置
const exportAllMockAPIs = async () => {
  exporting.value = true
  try {
    const response = await axios.get('http://localhost:8080/api/export')
    const data = response.data
    
    // 创建Blob对象并下载
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'smock_config_' + new Date().toISOString().slice(0, 10) + '.json'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exporting.value = false
  }
}

// 处理文件选择
const handleFileChange = (file) => {
  importFile.value = file.raw
}

// 从JSON文件导入
const importFromJSON = async () => {
  if (!importFile.value) {
    ElMessage.warning('请先选择文件')
    return
  }
  
  importing.value = true
  try {
    const reader = new FileReader()
    reader.onload = async (e) => {
      try {
        const content = e.target.result
        const data = JSON.parse(content)
        
        // 确认导入
        await ElMessageBox.confirm(
          `确定要导入${data.length || 0}个Mock API配置吗？这将覆盖同名的现有配置。`,
          '确认导入',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 发送导入请求
        await axios.post('http://localhost:8080/api/import', data)
        ElMessage.success('导入成功')
      } catch (error) {
        console.error('导入失败:', error)
        ElMessage.error('导入失败: ' + (error.message || '文件格式错误'))
      } finally {
        importing.value = false
      }
    }
    reader.readAsText(importFile.value)
  } catch (error) {
    console.error('读取文件失败:', error)
    ElMessage.error('读取文件失败')
    importing.value = false
  }
}

// 处理Swagger文件选择
const handleSwaggerFileChange = (file) => {
  swaggerForm.file = file.raw
}

// 从Swagger导入
const importFromSwagger = async () => {
  if (swaggerForm.importType === 'file' && !swaggerForm.file) {
    ElMessage.warning('请先选择Swagger文件')
    return
  }
  
  if (swaggerForm.importType === 'url' && !swaggerForm.url) {
    ElMessage.warning('请输入Swagger文档URL')
    return
  }
  
  importingSwagger.value = true
  try {
    let swaggerData
    
    if (swaggerForm.importType === 'file') {
      // 从文件读取
      const reader = new FileReader()
      const fileContent = await new Promise((resolve, reject) => {
        reader.onload = e => resolve(e.target.result)
        reader.onerror = reject
        reader.readAsText(swaggerForm.file)
      })
      
      // 根据文件扩展名判断格式
      const fileName = swaggerForm.file.name.toLowerCase()
      if (fileName.endsWith('.json')) {
        swaggerData = JSON.parse(fileContent)
      } else if (fileName.endsWith('.yaml') || fileName.endsWith('.yml')) {
        // 这里需要YAML解析库，实际项目中可以使用js-yaml等库
        ElMessage.error('暂不支持YAML格式，请使用JSON格式')
        importingSwagger.value = false
        return
      } else {
        ElMessage.error('不支持的文件格式')
        importingSwagger.value = false
        return
      }
    } else {
      // 从URL获取
      const response = await axios.get(swaggerForm.url)
      swaggerData = response.data
    }
    
    // 确认导入
    await ElMessageBox.confirm(
      '确定要从Swagger/OpenAPI规范导入API配置吗？',
      '确认导入',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 发送导入请求
    await axios.post('http://localhost:8080/api/import/swagger', {
      swagger: swaggerData,
      type: swaggerForm.importType
    })
    
    ElMessage.success('从Swagger导入成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('从Swagger导入失败:', error)
      ElMessage.error('从Swagger导入失败: ' + (error.message || '未知错误'))
    }
  } finally {
    importingSwagger.value = false
  }
}
</script>

<style scoped>
.import-export-container {
  padding: 20px;
}

.import-export-card {
  margin-top: 20px;
}

.export-section, .import-section {
  margin-bottom: 30px;
  padding: 20px;
}

.upload-area {
  margin: 20px 0;
}

.import-actions {
  margin-top: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.el-divider {
  margin: 30px 0;
}
</style>